﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BotonJXC.BLL;
using BotonJXC.Entity;
using NHibernate;
using BotonJXC.DAO;
using BotonJXC.Util;

namespace BotonJXC.Forms
{
    public partial class AcceptanceCheckMainForm : BaseMdiForm
    {
        public AcceptanceCheckMainForm()
        {
            InitializeComponent();
        }
        private Int32 pageSize = 1;
        private Int32 totalSize;
        WarehouseBLL WarehouseBLL = null;
        SupplierBLL SupplierBLL = null;
        AcceptanceBll AcceptanceBll = null;
        ProductBLL ProductBLL = null;
        Acceptance Acceptance = null;
        string[] type;
        private void SupplierMainForm_Load(object sender, EventArgs e)
        {
       
            windowsInit();
            loadDate();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void loadDate()
        {
            Acceptance AcceptanceSearch = new Acceptance();
            AcceptanceSearch.AcceptanceType = type[1];
            AcceptanceSearch.CreatePlace = type[0];

            if (AcceptanceBll == null) AcceptanceBll = new AcceptanceBll();

            PageModel<Acceptance> pageModel  = AcceptanceBll.FindPage(AcceptanceSearch, null, null, (pageSize - 1) * 1, 1);

            if (pageModel.Results.Count == 0)
            {
                this.deletedBtn.Enabled = false;
                this.auditBtn.Enabled = false;
                this.saveBtn.Enabled = false;
                auditfailBtn.Enabled = false;
            }
            else
            {

                //赋值
                foreach (Acceptance newAcceptance in pageModel.Results)
                {
                    this.Acceptance = newAcceptance;
                }
                //已审核
                if (Utils.ToString((Int32)Status.AuditPass).Equals(this.Acceptance.AuditStatus) || Utils.ToString((Int32)Status.AuditNoPass).Equals(this.Acceptance.AuditStatus))
                {
                    this.deletedBtn.Enabled = false;
                    this.auditBtn.Enabled = false;
                    this.saveBtn.Enabled = false;
                    auditfailBtn.Enabled = false;
                }
                else
                {
                    this.deletedBtn.Enabled = true;
                    this.auditBtn.Enabled = true;
                    this.saveBtn.Enabled = true;
                    auditfailBtn.Enabled = true;
                }
                //分页
                pageBtnControl(pageModel);

                this.SalesmanLabel.Text = "业务员: " + this.Acceptance.Salesman;
                this.MgtDepartmentCboBox.Text = Acceptance.MgDepartment == null ? "" : Acceptance.MgDepartment.DepName;
                this.FinDepartmentCboBox.Text = Acceptance.FinDepartment == null ? "" : Acceptance.FinDepartment.DepName;
                this.StoreAcceptanceCbox.Text = Acceptance.Store == null ? "" : Acceptance.Store.StoreName;
                this.UserWarehouseCBox.Text = Acceptance.Warehouse == null ? "" : Acceptance.Warehouse.Name;

                this.supplierIdText.Text = Acceptance.Supplier == null ? "" : Acceptance.Supplier.SupplierCode;
                this.supplierNameText.Text = Acceptance.Supplier == null ? "" : Acceptance.Supplier.SupplierName;

                this.ssupplierIdText.Text = Acceptance.SSupplier==null?"":Acceptance.SSupplier.SupplierCode;
                this.ssupplierNameText.Text = Acceptance.SSupplier == null ? "" : Acceptance.SSupplier.SupplierName;

                this.PaymentCbox.Text = Acceptance.Payment == null ? "" : Acceptance.Payment.PaymentName;
                this.RemarkText.Text = Acceptance.Remark;
                this.AuditRemarkText.Text = Acceptance.AuditRemark;

                this.createTimelabel.Text = "制单日期: " + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.Acceptance.CreateTime);

                if (Acceptance.Account != null)
                this.Accountlabel.Text = "制单人: " +  Acceptance.Account.Username;
                this.AuditTimelabel.Text = "审核日期:　" + string.Format("{0:yyyy/MM/dd HH:mm:ss}", this.Acceptance.AuditTime);
                if (Acceptance.AuditAccount != null)
                this.AuditAccountlabel.Text = "审核人:　" + Acceptance.AuditAccount.Username;
                if( Acceptance.Orders != null )
                this.Orderlabel.Text = "订单号: " + Acceptance.Orders.OrderSn;
                
                this.Stautslabel.Text = "单据状态: " + StatusUtil.getAuditString(Utils.ToInt( Acceptance.AuditStatus , 1));
                this.PrintTimeLabel.Text = "打印次数:　" + Acceptance.PrintTime;
                userDataGridView.Rows.Clear();
 
                foreach (AcceptanceProducts AcceptanceProducts in Acceptance.AcceptanceProductsList)
                {
                    int index = this.userDataGridView.Rows.Add();
                    this.userDataGridView.Rows[index].Cells["ProductId"].Value = AcceptanceProducts.Product.ProductId;
                    //货品编码
                    this.userDataGridView.Rows[index].Cells["ProductCode"].Value = AcceptanceProducts.Product.ProductCode;
                    //货品条码
                    this.userDataGridView.Rows[index].Cells["Barcode"].Value = AcceptanceProducts.Product.Barcode;
                   //货品名字
                    this.userDataGridView.Rows[index].Cells["ProductName"].Value = AcceptanceProducts.Product.ProductName;
                   
                    //单位
                    this.userDataGridView.Rows[index].Cells["Unit"].Value = AcceptanceProducts.Product.Unit == null ? "" : AcceptanceProducts.Product.Unit.UnitName;
                   //包装规格
                    this.userDataGridView.Rows[index].Cells["PackSpec"].Value = AcceptanceProducts.Product.ProductSpec;
                    if (Utils.ToString((Int32)Status.AuditPass).Equals(Acceptance.AuditStatus))
                    {
                        //税率
                        this.userDataGridView.Rows[index].Cells["TaxRate"].Value = AcceptanceProducts.TaxRate;
                    }
                    else {
                        //税率
                        this.userDataGridView.Rows[index].Cells["TaxRate"].Value = AcceptanceProducts.Product.TaxRate;
                    }
                    //保质期
                    this.userDataGridView.Rows[index].Cells["ShelfLife"].Value = AcceptanceProducts.Product.ShelfLife;
                    //件数
                    this.userDataGridView.Rows[index].Cells["numPcks"].Value = AcceptanceProducts.RealQuantity;
                    //验收数量
                    this.userDataGridView.Rows[index].Cells["AcceptanceNum"].Value = AcceptanceProducts.RealQuantity;

                    //订货数量
                    this.userDataGridView.Rows[index].Cells["ProductsNum"].Value = AcceptanceProducts.Quantity;
                    //含税进价 = 未税进价*（1+配送加价率+税率） 
                    this.userDataGridView.Rows[index].Cells["InPurPrice"].Value = AcceptanceProducts.Product.PurPrice * (1 + AcceptanceProducts.Product.AllocateAddRate + AcceptanceProducts.Product.TaxRate);
                    //未税进价
                    this.userDataGridView.Rows[index].Cells["PurPrice"].Value = AcceptanceProducts.Product.PurPrice;
                    //默认进价
                    this.userDataGridView.Rows[index].Cells["DefPurPrice"].Value = AcceptanceProducts.Price;
                    //验收金额
                    this.userDataGridView.Rows[index].Cells["Amount"].Value = AcceptanceProducts.Amount;
 
                }

                totalNumber();
               
            }

        }

        private void pageBtnControl(PageModel<Acceptance> pageModel)
        {
            this.totalSize = pageModel.PageCount;

            if (pageSize == totalSize)
            {
                this.next.Enabled = false;
            }
            else
            {
                this.next.Enabled = true;
            }
            if (pageSize == 1)
            {
                this.up.Enabled = false;
            }
            else
            {
                this.up.Enabled = true;
            }
        }
        /// <summary>
        /// 窗体初始化控件
        /// </summary>
        private void windowsInit() 
        {
              type = this.Tag.ToString().Split(',');

              if ("1".Equals(type[1]))
                {
                    this.Text = "供应商验收";
    
                }
              else if ("2".Equals(type[1]))
                {
                    this.Text = "采购验收";
                   
                }
              else if ("3".Equals(type[1]))
                {
                    storeAcceptance();
                    this.Text = "分店验收";
                }
                InitDepartment();
                InitStore();
                InitPaymets();
        }
        /// <summary>
        /// 分店验收初始化
        /// </summary>
        private void storeAcceptance() {
            this.Supplierlabel.Visible = false;
            this.supplierIdText.Visible = false;
            this.supplierNameText.Visible = false;

            this.ssupplierIdText.Visible = false;
            this.SsupplierLabel.Visible = false;
            this.ssupplierNameText.Visible = false;

            this.PaymentCbox.Visible = false;
            this.PaymentLabel.Visible = false;

            this.Orderlabel.Visible = false;

           this.Stautslabel.Location = new System.Drawing.Point(5, 96);
           this.Accountlabel.Location = new System.Drawing.Point(204, 96);
           this.createTimelabel.Location = new System.Drawing.Point(417, 96);

           this.AuditAccountlabel.Location = new System.Drawing.Point(5, 125);
           this.AuditTimelabel.Location = new System.Drawing.Point(204, 125);
           this.PrintTimeLabel.Location = new System.Drawing.Point(417, 125);

           this.Remarklabel.Location = new System.Drawing.Point(5, 154);
           this.AditAccountLabel.Location = new System.Drawing.Point(339, 154);
           this.RemarkText.Location = new System.Drawing.Point(64, 154);  
           this.AuditRemarkText.Location = new System.Drawing.Point(496, 154);

          // this.userDataGridView.Location = new System.Drawing.Point(0, 191);
          // this.userDataGridView.Size = new Size(870, 300); ;
           this.DefPurPrice.Visible = true;
           this.Amount.Visible = true;

           this.TaxRate.Visible = false;//税率
           this.numPcks.Visible = false;//件数
           this.InPurPrice.Visible = false;//含税进价
           this.ShelfLife.Visible = false;//保质期
           this.ProductsNum.Visible = false;

        }
        /// <summary>
        /// 配送中心采购验收/供应商验收
        /// </summary>
        private void supplierAcctance() { 
           
        }


        /// <summary>
        /// 初始化财务部部门 和管理部
        /// </summary>
        private void InitDepartment()
        {
            DepartmentBLL DepartmentBLL = new DepartmentBLL();
            IList<Department> DepartmentList = DepartmentBLL.FindAll();

            this.FinDepartmentCboBox.DataSource = DepartmentList;
            this.MgtDepartmentCboBox.DataSource = DepartmentList;

            MgtDepartmentCboBox.DisplayMember = "DepName";//显示字段
            MgtDepartmentCboBox.ValueMember = "DepId";//id值

            FinDepartmentCboBox.DisplayMember = "DepName";//显示字段
            FinDepartmentCboBox.ValueMember = "DepId";//id值

        }
        /// <summary>
        /// 分店
        /// </summary>
        private void InitStore()
        {
            StoreBLL StoreBLL = new StoreBLL();
            this.StoreAcceptanceCbox.DataSource = StoreBLL.FindAll();
            this.StoreAcceptanceCbox.DisplayMember = "StoreName";//显示字段
            this.StoreAcceptanceCbox.ValueMember = "StoreId";//id值
            InitWarehouse();
        }
        /// <summary>
        /// 加载结算方式
        /// </summary>
        private void InitPaymets()
        {

            PaymentBLL PaymentBLL = new PaymentBLL();
            IList<Payment> PaymentList = PaymentBLL.FindAll();
            PaymentCbox.DataSource = PaymentList;
            PaymentCbox.DisplayMember = "PaymentName";//显示字段
            PaymentCbox.ValueMember = "PaymentId";//id值
        }

        /// <summary>
        /// 初始化库存地
        /// </summary>
        private void InitWarehouse()
        {
            if (WarehouseBLL == null)
            {
                WarehouseBLL = new WarehouseBLL();
            }

            UserWarehouseCBox.DataSource = WarehouseBLL.FindByUserAll();
            UserWarehouseCBox.DisplayMember = "Name";//显示字段
            UserWarehouseCBox.ValueMember = "WarehouseId";//id值
 


        }
        /// <summary>
        /// 根据分店查找库存地
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StoreAcceptanceCbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            Store Store = (Store)this.StoreAcceptanceCbox.SelectedItem;
            if (WarehouseBLL == null) WarehouseBLL = new WarehouseBLL();
            UserWarehouseCBox.DataSource = WarehouseBLL.FindWarehouseByStoreId(Store.StoreId, true);
        }

    
        /// <summary>
        /// 供应商加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void supplierIdText_Leave(object sender, EventArgs e)
        {
            if (SupplierBLL == null) SupplierBLL = new SupplierBLL();
            Supplier Supplier = SupplierBLL.FindSupplier(this.supplierIdText.Text);
            if (Supplier == null)
            {
                MessageBox.Show("没有对应的供应商信息");
                this.supplierIdText.Text = "";
                this.supplierIdText.Tag = "";
                this.supplierNameText.Text = "";
            }
            else
            {
                this.supplierIdText.Tag = Supplier.SupplierId;
                this.supplierNameText.Text = Supplier.SupplierName;
            }
        }
        /// <summary>
        /// 供应商加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ssupplierIdText_Leave(object sender, EventArgs e)
        {
            if (SupplierBLL == null) SupplierBLL = new SupplierBLL();
            Supplier Supplier = SupplierBLL.FindSupplier(this.ssupplierIdText.Text);
            if (Supplier == null)
            {
                MessageBox.Show("没有对应的供应商信息");
                this.ssupplierIdText.Tag = "";
                this.ssupplierIdText.Text = "";
                this.ssupplierNameText.Text = "";
            }
            else
            {
                this.ssupplierIdText.Tag = Supplier.SupplierId;
                this.ssupplierNameText.Text = Supplier.SupplierName;
            }
        }
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addBtn_Click(object sender, EventArgs e)
        {
            this.saveBtn.Tag = "add";
            this.deletedBtn.Enabled = false;
            this.saveBtn.Enabled = true;
            this.userDataGridView.Rows.Clear();
            returnInit();
        }
        /// <summary>
        /// 重置表单
        /// </summary>
        private void returnInit()
        {
            this.AcceptanceSN.Text = "";
            this.supplierNameText.Text = "";
            this.supplierIdText.Text = "";
            this.ssupplierNameText.Text = "";
            this.ssupplierIdText.Text = "";

            this.Orderlabel.Text = "订单号: ";
            this.Stautslabel.Text = "单据状态: ";
            this.Accountlabel.Text = "制单人: ";
            this.createTimelabel.Text = "制单日期: ";
            this.AuditTimelabel.Text = "审核日期:";
            this.AuditAccountlabel.Text = "审核人:";
            this.PrintTimeLabel.Text = "打印次数:　";
            this.RemarkText.Text = "";
            this.AuditRemarkText.Text = "";
            this.TotalMoneylabel.Text = "进价金额: ";
            this.TotakAcceptancelabel.Text ="验收数量: ";

            this.StoreAcceptanceCbox.SelectedIndex = 0;
       
            this.PaymentCbox.SelectedIndex = 0;
            this.MgtDepartmentCboBox.SelectedIndex = 0;
            this.FinDepartmentCboBox.SelectedIndex = 0;
            this.UserWarehouseCBox.SelectedIndex = 0;

            //清空dateGridView
            this.userDataGridView.Rows.Clear();
        }

        private void next_Click(object sender, EventArgs e)
        {
            pageSize += 1;
            loadDate();
        }
    

        private void up_Click(object sender, EventArgs e)
        {
            pageSize -= 1;
            loadDate();
        }

        private void deletedBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除当前验收单吗？", "删除确认",
           MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                bool result = deleteAcceptance(Acceptance,3);
                if (result)
                {
                    MessageBox.Show("单据删除成功!");
                    loadDate();
                }
                else
                {
                    MessageBox.Show("单据删除失败!");
                }
            }

        }

        /// <summary>
        ///  验收单操作
        /// </summary>
        /// <returns></returns>
        private bool deleteAcceptance(Acceptance Acceptance,Int32 type)
        {
            bool result = false;
            if (Acceptance != null)
            {
                if (AcceptanceBll == null) AcceptanceBll = new AcceptanceBll(); 
                ITransaction trans = HBHelper.BeginTransaction();
                try
                {
                    if (type == 1)
                    {
                        AcceptanceBll.Save(Acceptance);
                    }
                    else if (type == 2) {
                        AcceptanceBll.Update(Acceptance);
                    }
                    else if (type == 3)
                    {
                        AcceptanceBll.Delete(Acceptance);
                    }
        
                    trans.Commit();
                    result = true;
                }
                catch (HibernateException ex)
                {
                    trans.Rollback();
                    result = false;
                    throw;

                }
                finally
                {
                    HBHelper.Close();
                }
             
            }
            return result;
        }

        private void saveBtn_Click(object sender, EventArgs e)
        {
            if ("add".Equals(this.saveBtn.Tag))
            {

                bool result = deleteAcceptance(getAcceptance(),1);
                if (result)
                {
                    MessageBox.Show("单据添加成功!");
                    loadDate();
                    this.saveBtn.Tag = "up";
                    this.saveBtn.Enabled = true;
                }
                else
                {
                    MessageBox.Show("单据添加失败!");
                }
            }
            else if ("up".Equals(this.saveBtn.Tag))
            {
                bool result = deleteAcceptance(getAcceptance(),2);
                if (result)
                {
                    MessageBox.Show("单据修改成功!");
                    loadDate();
                }
                else
                {
                    MessageBox.Show("单据修改失败!");
                }
            }
        }


        private Acceptance getAcceptance() {
            Acceptance newAcceptance = null;
            if ("add".Equals(this.saveBtn.Tag))
            {
                newAcceptance = new Acceptance();

                newAcceptance.Account = LoginForm.Account;
                newAcceptance.CreateTime = DateTime.Now;
                newAcceptance.AuditStatus = "1";
                newAcceptance.AcceptanceType=type[1] ;
                newAcceptance.CreatePlace = type[0];
                //单据编号newAcceptance
                newAcceptance.Salesman = "";
            }
            else {
                newAcceptance = this.Acceptance;
                newAcceptance.Salesman = LoginForm.Account.Username;
            }
            newAcceptance.MgDepartment = (Department)this.MgtDepartmentCboBox.SelectedItem;
            newAcceptance.FinDepartment = (Department)this.FinDepartmentCboBox.SelectedItem;
            newAcceptance.Store = (Store)this.StoreAcceptanceCbox.SelectedItem;
            newAcceptance.Warehouse = (Warehouse)this.UserWarehouseCBox.SelectedItem;
            int SupplierID = Utils.ToInt( this.supplierIdText.Tag ,0);
            if (SupplierID != 0)
                newAcceptance.Supplier = new Supplier(SupplierID);
            int SSupplierID = Utils.ToInt(this.ssupplierIdText.Tag, 0);
            if (SSupplierID!=0)
                newAcceptance.SSupplier = new Supplier(SSupplierID);

            newAcceptance.Payment = (Payment)this.PaymentCbox.SelectedItem;
            newAcceptance.Remark = this.RemarkText.Text;
            newAcceptance.AuditRemark = this.AuditRemarkText.Text;
            newAcceptance.AcceptanceProductsList = GetOutStocksProducts();
            return newAcceptance;
        }

        /// <summary>
        /// 获取货品信息
        /// </summary>
        /// <returns></returns>
        public IList<AcceptanceProducts> GetOutStocksProducts()
        {
            IList<AcceptanceProducts> oplist = new List<AcceptanceProducts>();
            for (int i = 0; i < this.userDataGridView.Rows.Count - 1; i++)//如果DataGridView中有空的数据，则提示数据输入不完整并退出添加，不包括标题行
            {
                AcceptanceProducts AcceptanceProducts = new AcceptanceProducts();
                Product Product = new Product();
                Product.ProductId = Utils.ToInt(userDataGridView["ProductId", i].Value, 0);
                AcceptanceProducts.Product = Product;

                AcceptanceProducts.Quantity = Utils.ToDouble(userDataGridView["ProductsNum", i].Value, 0);
                AcceptanceProducts.RealQuantity = Utils.ToDouble(userDataGridView["AcceptanceNum", i].Value, 0);
                AcceptanceProducts.Price = Utils.ToDouble(userDataGridView["DefPurPrice", i].Value, 0);
                //AcceptanceProducts.Price = this
                AcceptanceProducts.Amount = AcceptanceProducts.RealQuantity * AcceptanceProducts.Price;

                oplist.Add(AcceptanceProducts);
            }
            return oplist;
        }
        /// <summary>
        /// 审核通过
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void auditBtn_Click(object sender, EventArgs e)
        {
            auditAccptance(Utils.ToString((Int32)Status.AuditPass));
        }
        /// <summary>
        /// 拒审
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void auditfailBtn_Click(object sender, EventArgs e)
        {
            auditAccptance(Utils.ToString((Int32)Status.AuditNoPass));
        }
        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="AuditStatus"></param>
        private void auditAccptance(string AuditStatus)
        {
            this.Acceptance.AuditAccount = LoginForm.Account;
            this.Acceptance.AuditTime = DateTime.Now;
            this.Acceptance.AuditStatus = AuditStatus;

            bool result = deleteAcceptance(getAcceptance(), 2);
            if (result)
            {
                MessageBox.Show("单据审核成功!");
                this.loadDate();
            }
            else
            {
                MessageBox.Show("单据审核失败!");
            }
        }

        private void deleteProductBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要删除该行数据吗？", "删除确认",
               MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 确定 删除
                foreach (DataGridViewRow r in this.userDataGridView.SelectedRows)
                {
                    if (!r.IsNewRow)
                    {
                        userDataGridView.Rows.Remove(r);
                    }
                }
            }
        }
        /// <summary>
        /// 统计总算
        /// </summary>
        private void totalNumber()
        {
            Double TotakAcceptance = 0;//实际配出数，报损数量
    
            //进价金额
            Double TotalMoney = 0;
     
            for (int i = 0; i < this.userDataGridView.Rows.Count - 1; i++)//如果DataGridView中有空的数据，则提示数据输入不完整并退出添加，不包括标题行
            {
                // PlanQuantity = Utils.ToDouble( this.ProductsDataGridViewOrders\["PlanQuantity",i].Value.ToString() ,0); //计划配出数量
                // RealOutQuantity =//实际配出数量
                //  RealInQuantity = this.ProductsDataGridViewOrders.Rows[i].Cells["RealInQuantity"].Value  ;//实际配人数量
                // DefPurPrice= this.ProductsDataGridViewOrders.Rows[i].Cells["DefPurPrice"].Value;//默认进价
                // RealOutQuantity = this.ProductsDataGridViewOrders.Rows[i].Cells["RealOutQuantitys"].Value;//报损数量
            
               Double AcceptanceNum =Utils.ToDouble( this.userDataGridView["AcceptanceNum", i].Value , 0);//报损数量
               TotakAcceptance += AcceptanceNum;
                if ("3".Equals(type[1]))
                {
                    TotalMoney += (Utils.ToDouble(this.userDataGridView["DefPurPrice", i].Value, 0) * AcceptanceNum);
                }
                else {
                    TotalMoney += (Utils.ToDouble(this.userDataGridView["InPurPrice", i].Value, 0) * AcceptanceNum);
                }
            }
            //总数计算

            this.TotalMoneylabel.Text = "进价金额: " + TotalMoney;
            this.TotakAcceptancelabel.Text = "验收数量: " + TotakAcceptance;
            

        }

        private void userDataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            string parameter = userDataGridView.Columns[e.ColumnIndex].Name;
            if ("ProductCode".Equals(parameter) || "Barcode".Equals(parameter) || "ProductName".Equals(parameter))
            {
                string value = userDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null ? "" : userDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (!"".Equals(value))
                {
                    if (ProductBLL == null) ProductBLL = new ProductBLL();
                    Product Product = ProductBLL.FindProduct(parameter, value);
                    if (Product == null)
                    {
                        MessageBox.Show("没有对应的货品");
                        userDataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                    }
                    else
                    {
                        userDataGridView["ProductId", e.RowIndex].Value = Product.ProductId;
                        userDataGridView["ProductCode", e.RowIndex].Value = Product.ProductCode;
                        userDataGridView["Barcode", e.RowIndex].Value = Product.Barcode;
                        userDataGridView["ProductName", e.RowIndex].Value = Product.ProductName;
                        userDataGridView["Unit", e.RowIndex].Value = Product.Unit == null ? "" : Product.Unit.UnitName;
                        userDataGridView["PackSpec", e.RowIndex].Value = Product.ProductSpec;


                        //ProductsDataGridViewOrders["PurPrice", e.RowIndex].Value = Product.PurPrice;//未税进价

                        //ProductsDataGridViewOrders["AllocateAddRate", e.RowIndex].Value = Product.AllocateAddRate * 100 + "%";//配送加价率

                        userDataGridView["InPurPrice", e.RowIndex].Value =
                             Product.PurPrice * (1 + Product.TaxRate);//含税进价 = 未税进价*(1+税率)
                       //userDataGridView["DefPurPrice", e.RowIndex].Value = Product.DefPurPrice;//默认进价
                       
                        userDataGridView["TaxRate", e.RowIndex].Value = Product.TaxRate;//税率
                        //未税进价
                        this.userDataGridView["PurPrice", e.RowIndex].Value = Product.PurPrice;
                        //保质期
                        this.userDataGridView["ShelfLife", e.RowIndex].Value = Product.ShelfLife;

                    }
                }


            }
            if ("AcceptanceNum".Equals(parameter) || "DefPurPrice".Equals(parameter))
            {
                Double AcceptanceNum = Utils.ToDouble(userDataGridView["AcceptanceNum", e.RowIndex].Value, 0);
                Double DefPurPrice = Utils.ToDouble(userDataGridView["DefPurPrice", e.RowIndex].Value, 0);

                if (DefPurPrice != 0 && AcceptanceNum!= 0) {
                    userDataGridView["Amount", e.RowIndex].Value = AcceptanceNum * DefPurPrice;
                }
                
                totalNumber();
            }
            
        }
    }
}
